import 'babel-polyfill';
import axios from 'axios'
import {
  MessageBox,
  Message,
} from 'element-ui'; //element库的消息提示，可以不用

import Vue from 'vue';
import VueRouter from 'vue-router';

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(VueRouter);
import routes from '../router/router.config.js';

const router = new VueRouter(routes);


// const baseRequire = 'https://yk.shonemore.com/api/admin/';
const baseRequire = 'http://192.168.10.124/lianxi/public/index.php';

// 创建axios实例
let service = axios.create({
  baseURL: baseRequire,
});


// http响应拦截器
service.interceptors.response.use(res => {

    return res
  },
  error => {
    Message.error('服务器异常，请联系管理员')
    return Promise.reject(error)
  }
)

export default {


  httpRequest(url, data, method = 'get', msg = true) {
    let option = {
      url,
      method: 'get',
      params: data
    }
    if (method !== 'get') {
      option = {
        url,
        method,
        data,
      }
    }
    option.headers = {
      'Content-Type': 'application/json;charset=UTF-8',
      'token': localStorage.getItem('token') ? localStorage.getItem('token').replace(/"/g, "") : '',
    }
    return new Promise((resolve, reject) => {
      service(option).then(res => {
        let method = option.method
        console.log(res)
        if (res.data.code === 1) {
          if (method === 'get') {
            resolve(res.data.data)
          } else {
            if (msg) {
              if (method === 'delete') {
                Message.success('删除成功')
              }
              if (method === 'put') {
                Message.success('修改成功')
              }
              if (method === 'post') {
                Message.success('添加成功')
              }
            }


            resolve(res.data)
          }
        }
        // if (res.data.code === 1) {
        //   Message.error(res.data.message);
        // }
        if (res.data.code === 2) {
          // window.location.replace(mainUr

          MessageBox.alert('登陆失效，即将跳转登陆页面', {
            confirmButtonText: '确定',
            callback: action => {

              router.push({
                path: "/login"
              })
              router.go(0)
            }
          });
          // router.push({
          //   path: "/login"
          // })
        }

      })
    })
  },
  baseRequire
}
